<template>
  <div class="article-add-container">
    <el-row :gutter="20" justify="center">
      <el-col :span="12">
        <ossUpload :imageUrl="domain + detailData.src" :imgName="randomName" dirname="Article" @upload-img="handler">
        </ossUpload>
        <el-input placeholder="请输入标题" v-model="detailData.title" class="input-with-select" style="margin-bottom: 4px">
          <el-select v-model="detailData.type" slot="prepend" placeholder="请选择类别">
            <el-option v-for="item in types" :key="item.value" :label="item.label" :value="item.value"></el-option>
          </el-select>
        </el-input>
        <!--<el-input placeholder="请输入内容" v-model="detailData.title" style="margin-bottom: 4px">-->
        <!--<template slot="prepend">标题</template>-->
        <!--</el-input>-->
        <el-input placeholder="请输入内容" v-model="detailData.author" style="margin-bottom: 4px">
          <template slot="prepend">作者</template>
        </el-input>
      </el-col>
    </el-row>

    <mavon-editor v-model="detailData.content" @save="updateArticle" @imgAdd="imgUpload" class="editor-sty"
      :boxShadow="false" ref="md"></mavon-editor>
  </div>
</template>

<script>
  import OSS from "ali-oss";
  import md5 from "md5-js";
  import ossUpload from "@/components/ossUpload.vue";

  export default {
    name: "ArticleUpdate",
    data() {
      return {
        articleHtml: "",
        title: "",
        titleSrc: "", // 标题图片地址
        author: "",
        detailData: {},
        type: 0,
        types: [
          {
            label: "无",
            value: 0
          },
          {
            label: "科普攻略",
            value: 1
          },
          {
            label: "生存技巧",
            value: 2
          },
          {
            label: "游戏更新",
            value: 3
          },
          {
            label: "官方公告",
            value: 4
          },
          {
            label: "其它",
            value: 5
          }
        ]
      };
    },
    components: {
      ossUpload
    },
    computed: {
      randomName() {
        let time = new Date();
        return md5(time);
      }
    },
    activated() {
      this.getDetailData();
    },
    methods: {
      /**
       * 先获取详情，填充数据
       * */
      getDetailData() {
        this.axios
          .get("/article/single", {
            params: {
              id: this.$route.query.id
            }
          })
          .then(res => {
            this.detailData = res.data;
          });
      },
      /**
       * 保存文章
       * @param mdVal 生成的markdown文档，可以用marked解析来展示
       */
      async updateArticle(mdVal) {
        console.log(mdVal);
        try {
          const res = await this.axios.post("article/update", {
            _id: this.detailData._id,
            src: this.detailData.src,
            type: this.detailData.type,
            title: this.detailData.title,
            author: this.detailData.author,
            time: this.detailData.time,
            content: this.detailData.content
          });
          if (res.data.code === 0) {
            this.$router.push("/ArticleList");
          } else {
            this.$message.error(res.data.message);
          }
        } catch (error) {
          this.$message.error("输入的内容超出上限。");
        }
      },
      /**
       * 图片上传
       */
      imgUpload(filename, $file) {
        // oss配置
        const client = new OSS({
          endpoint: "oss-cn-beijing.aliyuncs.com",
          accessKeyId: "LTAI4FgrsFXo8ij335BxeRbp",
          accessKeySecret: "oG0PWkV0qOeDoJQfwEHOqIvTp16S0x",
          bucket: "stavebox"
        });
        // 图片路径拼接，dirName其实就是定义存在oss的哪个虚拟文件夹下的
        let time = new Date();
        let hash = md5(time);
        let imgType = $file.type.split("/")[1];
        let hashName = "Article/" + hash + "." + imgType;
        // 将文件流上传至oss
        client
          .put(hashName, $file)
          .then(res => {
            let imgUrl = "http://img.fireleaves.cn/" + res.name;
            this.$refs.md.$img2Url(filename, imgUrl);
          })
          .catch(err => {
            console.log(err);
          });
      },
      handler(src) {
        this.detailData.src = src;
      }
    }
  };
</script>

<style lang="scss">
  .article-add-container {
    .el-input__inner {
      min-width: 110px;
    }

    .el-input-group__prepend {
      min-width: 70px;
    }

    .oss-upload-container {
      .avatar-uploader .el-upload {
        border: 1px dashed #d9d9d9;
        border-radius: 6px;
        cursor: pointer;
        position: relative;
        overflow: hidden;
      }

      .avatar-uploader .el-upload:hover {
        border-color: #409eff;
      }

      .avatar-uploader-icon {
        font-size: 36px;
        color: #8c939d;
        width: 560px;
        height: 120px;
        line-height: 120px;
        text-align: center;
      }

      .avatar {
        width: 560px;
        height: auto;
        display: block;
      }
    }
  }
</style>

<style lang="scss" scoped>
  .article-add-container {
    padding: 16px;

    .editor-sty {
      z-index: 1;
      height: 80vh;
    }
  }
</style>